<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { formatDateTime } from '@/utils/dayjs'
import { getStockInfo } from '@/api/goodsSales'
import logger from '@/utils/logger'

// 使用defineModel替代props和emit
const selectedGoods = defineModel('modelValue', {
  type: Array,
  default: () => [],
})

const emit = defineEmits(['close'])

// 表格数据和加载状态
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 查询条件
const queryFields = ref({
  goodsName: '',
  goodsTypeName: '',
})

// 表格引用，用于操作表格选择
const tableRef = ref(null)

// 获取库存商品列表
const fetchStockData = async () => {
  loading.value = true
  try {
    const params = {
      queryFields: {
        goodsName: queryFields.value.goodsName,
        goodsTypeName: queryFields.value.goodsTypeName,
      },
      currentPage: currentPage.value,
      pageSize: pageSize.value,
    }
    const res = await getStockInfo(params)
    if (res.success) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0

      // 在表格数据更新后应用选中状态
      nextTick(() => {
        applySelection()
      })
    } else {
      ElMessage.error(res.msg || '获取库存商品列表失败')
    }
  } catch (error) {
    logger.error('获取库存商品列表失败', error)
    ElMessage.error('获取库存商品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchStockData()
}

// 重置搜索
const resetSearch = () => {
  queryFields.value = {
    goodsName: '',
    goodsTypeName: '',
  }
  currentPage.value = 1
  fetchStockData()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchStockData()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchStockData()
}

// 应用已选商品到表格
const applySelection = () => {
  if (!tableRef.value) return

  // 清除当前表格的选中状态
  tableRef.value.clearSelection()

  // 获取当前页的行数据
  const currentPageRows = tableData.value || []

  // 当前选中的ID列表
  const selectedIds = selectedGoods.value.map((item) => String(item.dealerGoodsStoreId))

  // 应用选中状态到当前页的行
  currentPageRows.forEach((row) => {
    if (selectedIds.includes(String(row.dealerGoodsStoreId))) {
      nextTick(() => {
        tableRef.value.toggleRowSelection(row, true)
      })
    }
  })
}

// 处理选择变更
const handleSelectionChange = (selection) => {
  // 获取当前页的行数据
  const currentPageRows = tableData.value || []
  const currentPageIds = currentPageRows.map((item) => String(item.dealerGoodsStoreId))

  // 保留不在当前页的已选项
  const itemsNotInCurrentPage = selectedGoods.value.filter(
    (item) => !currentPageIds.includes(String(item.dealerGoodsStoreId)),
  )

  // 添加当前页中选中的项
  const selectedFromCurrentPage = selection

  // 合并不在当前页的选中项和当前页新选中的项
  selectedGoods.value = [...itemsNotInCurrentPage, ...selectedFromCurrentPage]
}

// 确认选择
const confirmSelection = () => {
  emit('close')
}

// 取消选择
const cancelSelection = () => {
  emit('close')
}

onMounted(() => {
  fetchStockData()
})
</script>

<template>
  <div class="stock-selector">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="queryFields">
        <el-form-item label="商品名称" style="width: 250px">
          <el-input
            v-model="queryFields.goodsName"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><LineMdSearch /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="商品类别" style="width: 250px">
          <el-input
            v-model="queryFields.goodsTypeName"
            placeholder="请输入商品类别"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><LineMdSearch /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <template #icon>
              <el-icon><LineMdSearch /></el-icon>
            </template>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <template #icon>
              <el-icon><LineMdClose /></el-icon>
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        row-key="dealerGoodsStoreId"
        reserve-selection
        empty-text="只显示有库存数量、单价和没有被工会拒绝上架的商品"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="商品图片" width="100" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.goodsPicture"
              :src="row.goodsPicture"
              style="width: 50px; height: 50px; border-radius: 4px"
              :preview-src-list="[row.goodsPicture]"
              fit="cover"
              preview-teleported
            />
            <div v-else class="no-image">无图片</div>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" show-overflow-tooltip min-width="180" align="center">
          <template #default="{ row }">
            {{ row.goodsName }}
          </template>
        </el-table-column>
        <el-table-column label="商品类别" min-width="120" align="center">
          <template #default="{ row }">
            <el-tag>{{ row.dealerGoodsTypeName || '未分类' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="规格" min-width="100" align="center">
          <template #default="{ row }">
            <el-tag type="success">{{ row.specifications }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="有效期" min-width="200" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.periodStartingDate, 'YYYY-MM-DD') }} 至
            {{ formatDateTime(row.periodEndDate, 'YYYY-MM-DD') }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="库存" width="100" align="center" />
        <el-table-column prop="unitPrice" label="单价（元）" width="100" align="center" />
        <el-table-column prop="shippingFee" label="配送费（元）" width="120" align="center">
          <template #default="{ row }">
            {{ row.shippingFee || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="freeShipping" label="免配送费数量" width="130" align="center">
          <template #default="{ row }">
            {{ row.freeShipping || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="100" align="center" />
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 底部操作按钮 -->
    <div class="dialog-footer">
      <el-button @click="cancelSelection">
        <template #icon>
          <el-icon><LineMdClose /></el-icon>
        </template>
        取消
      </el-button>
      <el-button type="primary" @click="confirmSelection">
        <template #icon>
          <el-icon><LineMdPlus /></el-icon>
        </template>
        确定
      </el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.stock-selector {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 200px);
  gap: 15px;

  .search-container {
    background-color: #fff;
    border-radius: 8px;
    padding: 10px;
  }

  .table-container {
    flex: 1;
    min-height: 300px;
    background-color: #fff;
    border-radius: 8px;
    padding: 10px;
    overflow: auto;

    .no-image {
      width: 50px;
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #909399;
      background-color: #f5f7fa;
      font-size: 12px;
      border-radius: 4px;
      border: 1px dashed #d9d9d9;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    padding: 10px;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding-top: 10px;
    border-top: 1px solid #eee;
  }
}
</style>
